package com.yongbao.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.tuple.Pair;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author macbook
 */
public class SplitTimeRangeUtil {

    public static List<Pair<Date, Date>> splitTimeRange(Date startDate, Date endTimeDate) {
        List<Pair<Date, Date>> timeRanges = new ArrayList<>();
        LocalDateTime endTime = convert(endTimeDate);

        LocalDateTime currentStartTime = convert(startDate);
        LocalDateTime currentEndTime;

        while (currentStartTime.isBefore(endTime) || currentStartTime.isEqual(endTime)) {
            currentEndTime = currentStartTime.plusDays(6).withHour(23).withMinute(59).withSecond(59);
            if (currentEndTime.isAfter(endTime)) {
                currentEndTime = endTime;
            }

            Date start = DateUtil.parse(currentStartTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), DatePattern.NORM_DATETIME_PATTERN).toJdkDate();
            Date end = DateUtil.parse(currentEndTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), DatePattern.NORM_DATETIME_PATTERN).toJdkDate();
            timeRanges.add(Pair.of(start, end));

            currentStartTime = currentEndTime.plusSeconds(1);
        }

        return timeRanges;
    }

    public static LocalDateTime convert(Date date) {
        Instant instant = date.toInstant();
        // 将Instant对象转换为LocalDateTime对象
        return instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
